using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace OpenSocial.Net
{
	public class ProviderBase
	{
		#region Declarations

		protected string _authToken = string.Empty;
		protected readonly string _domain = string.Empty;

		#endregion Declarations

		#region Properties

		public string AuthToken
		{
			get { return _authToken; }
			set { _authToken = value; }
		}

		public string Domain
		{
			get { return _domain; }
		}

		#endregion Properties

		#region Constructor

		internal protected ProviderBase(string domain)
		{
			_domain = domain;
		}

		internal protected ProviderBase(string domain, string authToken)
		{
			_authToken = authToken;
			_domain = domain;
		}

		#endregion Constructor


		/// <summary>
		/// Gets the response data from the request.
		/// </summary>
		/// <param name="req">The HttpWebRequest to retrieve a response from.</param>
		/// <returns></returns>
		internal protected string GetData(HttpWebRequest req)
		{
			HttpWebResponse resp = null;

			try
			{
				//get the response
				resp = (HttpWebResponse)req.GetResponse();
				Stream receiveStream = resp.GetResponseStream();
				Encoding encode = Encoding.GetEncoding("utf-8");
				// Pipes the stream to a higher level stream reader with the required encoding format. 
				StreamReader readStream = new StreamReader(receiveStream, encode);
				Char[] read = new Char[256];
				// Reads 256 characters at a time.
				StringBuilder sb = new StringBuilder();
				int count = readStream.Read(read, 0, 256);
				while (count > 0)
				{
					// Dumps the 256 characters on a string and displays the string to the console.
					String str = new String(read, 0, count);
					sb.Append(str);
					count = readStream.Read(read, 0, 256);
				}

				return sb.ToString();
			}
			finally
			{
				if (resp != null)
				{
					resp.Close();
				}
			}
		}

		/// <summary>
		/// Gets open social data from the given Url.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <returns></returns>
		internal protected string GetOpenSocialData(string url)
		{
			return GetOpenSocialData(url, _authToken);
		}

		/// <summary>
		/// Gets open social data from the given Url including the Authorization header.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="authToken">The authorization token.</param>
		/// <returns></returns>
		internal protected string GetOpenSocialData(string url, string authToken)
		{
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

			//add authorization header if available
			if (string.IsNullOrEmpty(authToken) == false)
			{
				string authHeaderValue = string.Format("GoogleLogin auth={0}", authToken);
				req.Headers.Add("Authorization", authHeaderValue);
			}

			string returnData = GetData(req);
			return (returnData);
		}
	}
}
